package com.jiangnan.components;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class CustomSwitchButton extends JComponent {
    private boolean switchedOn = false;

    public CustomSwitchButton() {
        setPreferredSize(new Dimension(50, 25));
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                switchedOn = !switchedOn;
                repaint();
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 绘制按钮背景
        g2d.setColor(Color.GRAY);
        g2d.fillRect(0, 0, getWidth(), getHeight());

        // 绘制按钮开关
        g2d.setColor(switchedOn ? Color.GREEN : Color.RED);
        g2d.fillOval(switchedOn ? getWidth() - getHeight() : 0, 0, getHeight(), getHeight());

        g2d.dispose();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Custom Switch Button");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(100, 100);

            CustomSwitchButton switchButton = new CustomSwitchButton();
            frame.add(switchButton);
            frame.setVisible(true);
        });
    }
}
